package com.io.service.impl;


import com.io.service.FileServer;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class FileServerImpl implements FileServer {


//    @Value("${UPLOAD_PATH}")
    private String UPLOAD_PATH = "E:/File/image/upload";

    @Override
    public Map<String,String> upload(MultipartFile image)  {
        HashMap<String,String> hashMap = new HashMap();

        if (image==null) {
            return null;
        }
        String filename = image.getOriginalFilename();
        hashMap.put("filename",filename);
        String uuid = UUID.randomUUID().toString().replace("-","");
        filename=uuid+"_"+filename;
        String dateTime = new DateTime().toString("yyyy/MM/dd");
        if (!image.isEmpty()) {
            try {
                    Path directory = Paths.get(UPLOAD_PATH);

                if(!Files.exists(directory)){
                    Files.createDirectories(directory);
                }
                File upload = new File(directory+"\\"+dateTime);
                if(!upload.exists()){
                    upload.mkdirs();
                }
                String filePath = upload+"\\"+filename;
                File saveDir = new File(filePath);
                image.transferTo(saveDir);
                filePath ="/Document/"+ dateTime+"/"+filename;
                hashMap.put("filePath",filePath);

                return hashMap;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
             return null;
    }
}
